package components.utils
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFormat;
    import flash.utils.getTimer;

    public class FPSCounter extends Sprite
    {
        private static const CALC_PERIOD : int = 500;
        
        private var m_label         : TextField;        
        private var m_startFrameMS  : int;
        private var m_framesCounter : int;
        
        public function FPSCounter()
        {
            super();
            
            configureLabel();
            
            m_startFrameMS  = flash.utils.getTimer();
            m_framesCounter = 0;
            
            this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }
        
        private function configureLabel() : void
        {
            var format : TextFormat = new TextFormat("Courier New", 14, 0xFFFF00, true);
            
            m_label = new TextField();
            m_label.selectable        = false;
            m_label.mouseEnabled      = false;
            m_label.background        = true;
            m_label.backgroundColor   = 0x000000;
            m_label.autoSize          = TextFieldAutoSize.LEFT;
            m_label.defaultTextFormat = format;
            
            this.addChild(m_label);
        }
        
        private function updateLabel(fps : Number) : void
        {
            m_label.text = "FPS: " + String(fps.toFixed(2));
        }
        
        private function onEnterFrame(event : Event) : void
        {
            m_framesCounter++;
            
            const curFrameMS : int = flash.utils.getTimer();
            if(curFrameMS - m_startFrameMS >= CALC_PERIOD)
            {
                updateLabel(1000 * m_framesCounter / (curFrameMS - m_startFrameMS));
                
                m_startFrameMS  = curFrameMS;
                m_framesCounter = 0;
            }
        }
    }
}